<?php
/*
 * 主要功能:文件緩存
 *
 * dreamxyp(QQ:31996798) - PHP - class.dc.php
 * coding:夏一平
 * 創建時間:2006-10-30
 */
class dc
{
	//set
	static protected $fileDir 	= FILE_DATA_CACHE;
	static protected $memDir  	= '';
	static protected $zip  		= 0;//0為不壓
	static protected $json		= 0;//
	static protected $DirCount	=100;
	//cache
	static protected $fFile;
	static protected $mFile;	
	/*
	 * 功能:讀
	 */
	static public function get($key,$time=300,$skey='dc')
	{
		self::getFileName($key,$skey);
		if(self::$memDir)
		{//內存
			$mt = @filemtime(self::$mFile);
			if($mt > (time()-$time))
			{
				return self::de(file_get_contents(self::$mFile));
			}
		}
		//文件
		$mt = @filemtime(self::$fFile);
		if($mt > (time()-$time))
		{
			return self::de(file_get_contents(self::$fFile));
		}
		return false;
	}
	/*
	 * 功能:寫
	 */
	static public function put($key,$var,$skey='dc')
	{
		self::getFileName($key,$skey);
		$var = self::en($var);
		if(self::$memDir)
		{//內存
			g::write(self::$mFile,$var);
		}else
		{
			g::write(self::$fFile,$var);
		}
	}
	/*
	 * 功能:刪
	 */
	static public function del($key,$skey='dc')
	{
		self::getFileName($key,$skey);
		if(file_exists(self::$fFile))unlink(self::$fFile);
		if(self::$memDir) if(file_exists(self::$mFile))unlink(self::$mFile);
	}
	/*
	 * 功能:設定
	 */
	static public function set($config)
	{
		if(is_array($config))
		{
			foreach($config as $k => $v)
			{
				if(isset(self::$$k))self::$$k = $v;
			}	
		}
	}
	/*
	 * 功能:得到文件名
	 */
	static public function getFileName($key,$skey='dc')
	{
		$key = $key.'.'.$skey;
		$md5 = md5($key);
		for ($i = 0; $i<strlen($md5); $i++)
		{
			$VarOrd1 += ord($md5{$i})*$i;  
			$VarOrd2 += ord($md5{$i})*($i*2+1);		
		}
		$VarOrd1 %= self::$DirCount;	
		$VarOrd2 %= self::$DirCount;
		//文件
		self::$fFile = self::$fileDir.$VarOrd1.'/'.$VarOrd2;
		g::dir(self::$fFile,true);
		self::$fFile .= '/'.$md5.'.'.$skey;
		if(self::$memDir)
		{	//內存
			self::$mFile = self::$memDir.$VarOrd1.'/'.$VarOrd2;
			g::dir(self::$mFile,true);
			self::$mFile .= '/'.$md5.'.'.$skey;
		}
		return self::$fFile;
	}
	protected function de(&$vars)
	{
		if(self::$zip)
		{
			$vars =gzinflate($vars);
		}
		return unserialize($vars);
	}
	protected function en(&$vars)
	{
		$vars =serialize($vars);
		if(self::$zip)
		{
			$vars =gzdeflate($vars,self::$zip);
		}
		return $vars;
	}	
}
?>